package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.MemberFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 做cookie刷新,浏览器中也要刷新
 */
@Component
public class CookieRefreshFilter extends ZuulFilter {
    @Autowired
    private MemberFeignApi memberFeignApi;
    /**
     * 声明filer的类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
     * 设置优先级,返回值越小优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 如果方法返回true就进入到run方法中
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //判断用户是否携带者token,token是在cookie中,可以中请求对象中获取
        RequestContext currenContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currenContext.getRequest();
        String token = CookieUtil.getToken(request, "userToken");
        if (token==null){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currenContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currenContext.getRequest();
        HttpServletResponse response = currenContext.getResponse();
        String token = CookieUtil.getToken(request, "userToken");
        if (token!=null){
            //远程调用会员服务,延长redis过期时间
            Result<Boolean> result = memberFeignApi.refreshToken(token);
            if (request!=null&&result.getCode()==200&&result.getData()){
                //延长cookie的过期时间
                CookieUtil.addCoolie("userToken", token, 1800, response);
            }
        }
        //设置成false就不会再去执行后面的filter
        currenContext.setSendZuulResponse(false);
        return null;
    }
}
